package THU.hxdExp;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;
import com.datastax.driver.core.querybuilder.QueryBuilder;

public class CassandraCluster {

	/** !this method MUST be called at least once! */
	public static CassandraCluster getInstance() {
		if (myCluster == null)
			myCluster = new CassandraCluster();
		return myCluster;
	}

	protected static CassandraCluster myCluster;

	private String[] nodes = { "192.168.3.17" };
	// one cluster for per physical
	private Cluster cluster;
	// one session for per ks
	public Session session;

	private static String selectCql = "select * from %s.%s where equip='%s' and time=%s;";

	private static String ks = "mytest";
	private static String cf = "usertable";

	private CassandraCluster() {
		connect(nodes);
	}

	public Session getSession() {
		return session;
	}

	public void connect(String[] nodes) {
		if (nodes == null || nodes.length == 0)
			return;
		List<InetAddress> addresses = new ArrayList<InetAddress>();
		for (String node : nodes) {
			try {
				addresses.add(InetAddress.getByName(node));
			} catch (UnknownHostException e) {
				System.out.println("connect error : " + e.getMessage());
			}
		}
		cluster = Cluster.builder().addContactPoints(addresses).build();

		try {
			session = cluster.connect();
		} catch (Exception e) {
			System.out.println("connect error : " + e.getMessage());
		}
	}

	public void close() {
		if (session != null) {
			session.close();
			session = null;
		}
		if (cluster != null) {
			cluster.close();
			cluster = null;
		}
		myCluster = null;
	}

	public ResultSet insert(String equip, String time, String value) {
		Statement statement = QueryBuilder.insertInto(ks, cf).value("equip", equip).value("time", time).value("value",
				value);
		ResultSet rSet = session.execute(statement);
		return rSet;
	}

	public ResultSet select(String equip, String time) {
		ResultSet rSet = null;
		rSet = session.execute(String.format(selectCql, ks, cf, equip, time));

		return rSet;
	}

	public ResultSet selectBulider(String equip, String time) {
		ResultSet rSet = null;
		rSet = session.execute(String.format(selectCql, ks, cf, equip, time));
		return rSet;
	}

	public static void main(String[] args) {
		CassandraCluster cluster = new CassandraCluster();
		String equip = "mechine";
		String time = "now";
		String value = "123";
		//cluster.insert(equip, time, value);
		cluster.select(equip, time);
		System.out.println("done!");
		cluster.close();
	}
}
